# -*- coding: utf-8 -*-
# @Time    : 2025/1/8 上午10:05
# @Author  : ysj
# @FileName: size_recall.py
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/ydscc?type=blog
import os

import cv2
import json
import numpy as np

def resize_and_adjust_polygons(image_path, json_path, output_image_path, output_json_path, target_size=(640, 640)):
    # 读取图像
    image = cv2.imread(image_path)
    h, w = image.shape[:2]

    # 计算缩放比例和填充
    scale = min(target_size[0] / w, target_size[1] / h)
    new_w, new_h = int(w * scale), int(h * scale)
    pad_w, pad_h = target_size[0] - new_w, target_size[1] - new_h
    pad_left, pad_top = pad_w // 2, pad_h // 2

    # 缩放图像
    resized_image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)

    # 填充图像
    padded_image = cv2.copyMakeBorder(
        resized_image, pad_top, pad_h - pad_top, pad_left, pad_w - pad_left,
        cv2.BORDER_CONSTANT, value=(114, 114, 114)  # 灰色填充
    )

    # 保存处理后的图像
    cv2.imwrite(output_image_path, padded_image)

    # 读取 JSON 标注数据
    with open(json_path, 'r') as f:
        annotations = json.load(f)

    # 调整多边形标注点
    for obj in annotations['shapes']:
        points = obj['points']  # 多边形点列表，形如 [[x1, y1], [x2, y2], ...]
        adjusted_points = []
        for x, y in points:
            # 调整点坐标
            new_x = x * scale + pad_left
            new_y = y * scale + pad_top
            adjusted_points.append([new_x, new_y])
        # 更新多边形点
        obj['points'] = adjusted_points

    # 保存调整后的 JSON 数据
    with open(output_json_path, 'w') as f:
        json.dump(annotations, f, indent=4)

    print("Processing completed: ",output_json_path)

# 示例用法

if __name__ == '__main__':

    file_path ='C:\Al\Software\AI_Model\Project\yolov5\yolov5\my_data\office_data'

    for filename in os.listdir(file_path):
        if filename.endswith('.jpg'):
            image_path = os.path.join(file_path, filename)
            json_path = os.path.join(file_path, filename.replace('.jpg', '.json'))
            resize_and_adjust_polygons(
                image_path=image_path,
                json_path=json_path,
                output_image_path=image_path,
                output_json_path=json_path
            )
